package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.TurnoutTemp;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    private final OrderMapper orderMapper;
    private final UserMapper userMapper;
    private final WorkspaceService workspaceService;

    @Autowired
    public ReportServiceImpl(OrderMapper orderMapper, UserMapper userMapper, WorkspaceService workspaceService) {
        this.orderMapper = orderMapper;
        this.userMapper = userMapper;
        this.workspaceService = workspaceService;
    }

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        String dateRes = StringUtils.join(dateList, ",");

        // 查询每个日期对应的订单总额
        List<TurnoutTemp> turnoverList = orderMapper.selectTurnoverByDateRange(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        BigDecimal[] turnoverRes = new BigDecimal[dateList.size()];
        Arrays.fill(turnoverRes, BigDecimal.ZERO);
        turnoverList.forEach(t -> {
            int index = dateList.indexOf(t.getDate());
            turnoverRes[index] = t.getAmount();
        });
        return TurnoverReportVO.builder()
                .dateList(dateRes)
                .turnoverList(StringUtils.join(turnoverRes, ","))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        String dateRes = StringUtils.join(dateList, ",");

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        dateList.forEach(date -> {
            LocalDateTime beginDate = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endDate = LocalDateTime.of(end, LocalTime.MAX);
            Map<String, Object> map = new HashMap<>();
            map.put("end", endDate);
            Integer totalUser = userMapper.countByMap(map);
            map.put("begin", beginDate);
            Integer newUser = userMapper.countByMap(map);

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        });
        return UserReportVO.builder()
                .dateList(dateRes)
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        String dateRes = StringUtils.join(dateList, ",");
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer totalValidOrderCount = 0;
        for (LocalDate date : dateList) {
            Map<String,Object> map = new HashMap<>();
            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));
            Integer orderCount = orderMapper.countByMap(map);
            orderCountList.add(orderCount);
            totalOrderCount += orderCount;

            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            validOrderCountList.add(validOrderCount);
            totalValidOrderCount += validOrderCount;
        }
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = (double)totalValidOrderCount / (double)totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(dateRes)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(totalValidOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(
                LocalDateTime.of(begin, LocalTime.MIN),
                LocalDateTime.of(end, LocalTime.MAX)
        );

        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(numbers, ","))
                .build();
    }

    @Override
    public void exportData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(
                LocalDateTime.of(begin, LocalTime.MIN),
                LocalDateTime.of(end, LocalTime.MAX)
        );

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            if (in != null) {
                XSSFWorkbook excel = new XSSFWorkbook(in);
                XSSFSheet sheet = excel.getSheet("Sheet1");
                sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + " 至 " + end);

                sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
                sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
                sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
                sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

                for (int i = 0; i < 30; i++) {
                    LocalDate date = begin.plusDays(i);
                    BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                    XSSFRow row = sheet.getRow(i + 7);
                    row.getCell(1).setCellValue(String.valueOf(date));
                    row.getCell(2).setCellValue(data.getTurnover());
                    row.getCell(3).setCellValue(data.getValidOrderCount());
                    row.getCell(4).setCellValue(data.getOrderCompletionRate());
                    row.getCell(5).setCellValue(data.getUnitPrice());
                    row.getCell(6).setCellValue(data.getNewUsers());
                }
                ServletOutputStream out = response.getOutputStream();
                excel.write(out);

                excel.close();
                out.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<LocalDate> getDateList(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        LocalDate tmp = begin;
        dateList.add(tmp);
        while (!tmp.equals(end)){
            tmp = tmp.plusDays(1);
            dateList.add(tmp);
        }
        return dateList;
    }
}
